import 'dart:convert';
import 'dart:core';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

import '../Gesture/GestureDetectorConflictTest.dart';
import '../Gesture/GestureDetectorHitTest.dart';
import '../Gesture/NotificationInterruptTest.dart';

///三方库Dio请求的使用
class HttpDioUse extends StatelessWidget {
  Dio dio = Dio();

  Map<dynamic, dynamic> parseData(String data) {
    return json.decode(data) as Map<dynamic, dynamic>;
  }

  void setHttpRequestHead() async {
    Response<String> response = await dio.get(
        "https://admin.leke.cn/eb/admin/apk/checkUpdate",
        queryParameters: {"deviceType": "HC_TEMPERATURE", "versionCode": 1042});
    print("结果：${response.data}");

    ///常规转换 方式
    Map resultMap = json.decode(response.data!);
    var result = BaseHttpResult.fromJson(resultMap);
    var data = UpdateVersionBean.fromJson(result.data);

    print("json解析结果：${data.toString()}----${data.forceUpdate}");


    var option = Options();
    option.method = "get";

    //请求结果为string
    final Response<String> response1 = await dio.request<String>(
      "https://admin.leke.cn/eb/admin/apk/checkUpdate",
      queryParameters: {"deviceType": "HC_TEMPERATURE", "versionCode": 1042},
      options: option,
    );
    var data1 = response1.data.toString();
    //parseData(data1)： string转化为json，
    var result1 = BaseHttpResult.fromJson(parseData(data1));
    var bean1 = UpdateVersionBean.fromJson(result1.data);

    print("json解析结果1：${bean1.toString()}----${bean1.forceUpdate}");
    ///这里有错误
    // Response<BaseHttpResult> response=await dio.get("https://admin.leke.cn/eb/admin/apk/checkUpdate",queryParameters:{"deviceType":"HC_TEMPERATURE","versionCode":1042});
    // print("结果：${response.data}");
    // ///常规转换 方式
    // print("json解析结果：${response.data?.data.toString()}");
  }

  var progressTarget = 0;

  void downloadApk() async {
    Response response = await dio.download(
        "https://file.leke.cn/fs/2022-01-17/GH/HBCY/XJYZH8ORPBR3UWUV2XMSIENDTUCQRK.apk",
        '/data/user/0/com.example.first_flutter_project/app_flutter/eccard.apk',
        onReceiveProgress: (receivedBytes, totalBytes) {
      print("接收receivedBytes：${receivedBytes}---totalBytes：$totalBytes");
    });
    print("结果：${response.data}");
  }

  Future<String> _getLocalFile() async {
    // 获取应用目录对应：/data/user/0/com.example.first_flutter_project/app_flutter
    String dir = (await getApplicationDocumentsDirectory()).path;
    // String directoryPath = root.path;
    return dir;
  }




  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        children: [
          ElevatedButton(
            child: Text("dio请求更新数据,请求数据"),
            onPressed: setHttpRequestHead,
          ),
          ElevatedButton(
            child: Text("dio请求，下载文件"),
            onPressed: downloadApk,
          ),
        ],
      ),
    );
  }
}



class BaseHttpResult {
  int code = 0;
  String? message;
  String? time = "";
  bool? success;
  Map<dynamic, dynamic> data;

  BaseHttpResult.fromJson(Map<dynamic, dynamic> jsonMap)
      : code = jsonMap['code'],
        time = jsonMap['time'],
        success = jsonMap['success'],
        data =jsonMap['data'],
        message = jsonMap['message'];

  Map<String, dynamic> toJson() => <String, dynamic>{
        'code': code,
        'time': time,
        'success': success,
        'data': data,
        'message': message,

      };

  @override
  String toString() {
    return 'BaseHttpResult{code: $code, message: $message, time: $time, success: $success, data: $data}';
  }
}

class BaseBean{
  BaseBean.fromJson(Map<dynamic, dynamic> json);
}

class UpdateVersionBean extends BaseBean{
  int versionCode = -1;
  int id = -1;
  String? versionName;
  String? updateTip;
  String? apkUrl;
  bool? isNeedUpdate;
  bool? forceUpdate;

  UpdateVersionBean.fromJson(Map<dynamic, dynamic> json)
      : versionCode = json['versionCode'],
        id = json['id'],
        versionName = json['versionName'],
        updateTip = json['updateTip'],
        apkUrl = json['apkUrl'],
        isNeedUpdate = json['isNeedUpdate'],
        forceUpdate = json['forceUpdate'], super.fromJson(json);

  Map<String, dynamic> toJson() => <String, dynamic>{
        'versionCode': versionCode,
        'id': id,
        'versionName': versionName,
        'updateTip': updateTip,
        'apkUrl': apkUrl,
        'isNeedUpdate': isNeedUpdate,
        'forceUpdate': forceUpdate,
      };

  @override
  String toString() {
    return 'UpdateVersionBean{versionCode: $versionCode, id: $id, versionName: $versionName, updateTip: $updateTip, apkUrl: $apkUrl, isNeedUpdate: $isNeedUpdate, forceUpdate: $forceUpdate}';
  }
}
